import Http from "./http.js";
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatDate = (date,yearRange=0,monthRange=0,dayRange=0) =>{
  const year = date.getFullYear()+yearRange
  const month = date.getMonth() + 1 +monthRange
  const day = date.getDate()+monthRange
  return [year, month, day].map(formatNumber).join('-')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}



const transformDict = (arr, dicts, replaceKey1 = "status") => {
  if (Array.isArray(arr)) {
    arr.forEach((item1, index1, self1) => {
      dicts.forEach((item2, index2, self2) => {
        if (item1.status == item2.code) {
          item1[replaceKey1] = {
            ...item2
          }
        }
      })
    })
  }
  console.log(arr)
  return arr;
}


const transformImageSrcBase64 = (arr, replaceKey) => {
  if (Array.isArray(arr)) {
    if (replaceKey) {
      arr.forEach((item, index, self) => {
        if (!item[replaceKey]) item[replaceKey] = "";
        let img = wx.base64ToArrayBuffer(item[replaceKey])
        let baseImg = 'data:image/jpeg;base64,' + wx.arrayBufferToBase64(img);
        item[replaceKey] = baseImg;
      })
      console.log('transformImageSrcBase64', arr)
      return arr;
    }else{
      let newArr=[];
      arr.forEach((item, index, self) => {
        let img = wx.base64ToArrayBuffer(item)
        let baseImg = 'data:image/jpeg;base64,' + wx.arrayBufferToBase64(img);
        newArr.push(baseImg);
      })
      console.log('transformImageSrcBase64', newArr)
      return newArr;
    }
  }else{
    if(!arr)  return arr;
    let img = wx.base64ToArrayBuffer(arr)
    let baseImg = 'data:image/jpeg;base64,' + wx.arrayBufferToBase64(img);
    return baseImg;
  }
 
}



const transformFullSrc = (src) => {
  let sessionId = wx.getStorageSync("sessionid");
  if(Array.isArray(src)){
    let newArr=[]
    src.forEach((item,index,self)=>{
      let res = Http.apiUrl + Http.imgUrl + "?imagePath=" + item +
      "&" + sessionId;
      newArr.push(res);
    })
    return newArr;
  }else{
    
    let res = Http.apiUrl + Http.imgUrl + "?imagePath=" + src +
      "&" + sessionId;
    return res;
  }
 
}

module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  transformDict: transformDict,
  transformImageSrcBase64: transformImageSrcBase64,
  transformFullSrc: transformFullSrc
}